package com.shadow.baiqun.delegate.room.check;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.shadow.baiqun.R;
import com.shadow.baiqun.R2;
import com.shadow.baiqun.delegate.common.ResultConverter;
import com.shadow.baiqun.event.ScanInfoEvent;
import com.shadow.core.delegate.RxShadowDelegate;
import com.shadow.core.net.callback.IError;
import com.shadow.core.net.callback.ISuccess;
import com.shadow.core.net.rx.RxRestClient;
import com.shadow.core.util.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author zy
 *         on 2018/7/13
 */
public class CheckTaskCommitDelegate extends RxShadowDelegate {
    private static final String ENTITY = "entity";

    public static CheckTaskCommitDelegate create(BoardInfoEntity boardInfoEntity) {
        final CheckTaskCommitDelegate contentDelegate = new CheckTaskCommitDelegate();
        final Bundle bundle = new Bundle();
        bundle.putSerializable(ENTITY, boardInfoEntity);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.et_part_name)
    TextView mTvName;
    @BindView(R2.id.et_part_code)
    TextView mTvCode;
    @BindView(R2.id.et_supplier_name)
    TextView mTvCount;
    @BindView(R2.id.et_good_parts_count)
    EditText mEtGoodCount;
    @BindView(R2.id.et_bad_part_count)
    EditText mEtBadCount;

    private BoardInfoEntity mBoardInfoEntity;
    //零件总量
    private int mAllCount;
    private boolean flag = true;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mBoardInfoEntity = (BoardInfoEntity) bundle.getSerializable(ENTITY);
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_check_task_commit;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pop();
                }
            });
            mToolbar.setTitle("检测");
        }
        if (mBoardInfoEntity != null) {
            mTvName.setText(mBoardInfoEntity.getPartName());
            mTvCode.setText(mBoardInfoEntity.getPartNum());
            mTvCount.setText(String.valueOf(mBoardInfoEntity.getPartCount()));
            mAllCount = mBoardInfoEntity.getPartCount();
            mEtGoodCount.setText(String.valueOf(mBoardInfoEntity.getGoodCount()));
            mEtGoodCount.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    if (!TextUtils.isEmpty(editable.toString())) {
                        if (flag) {
                            flag = false;
                            int good = Integer.parseInt(editable.toString());

                            if (mTvCount != null) {
                                mTvCount.setText(editable.toString());
                            }
                            if (mEtBadCount != null) {
                                mEtBadCount.setText(String.valueOf(mAllCount - good));
                            }
                            if (mBoardInfoEntity != null) {
                                mBoardInfoEntity.setPartCount(good);
                                mBoardInfoEntity.setGoodCount(good);
                                mBoardInfoEntity.setBadCount(mAllCount - good);
                            }
                        } else {
                            flag = true;
                        }
                    }
                }
            });
            mEtBadCount.setText(String.valueOf(mBoardInfoEntity.getBadCount()));
            mEtBadCount.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    if (!TextUtils.isEmpty(editable.toString())) {
                        if (flag) {
                            flag = false;
                            int bad = Integer.parseInt(editable.toString());
                            if (mTvCount != null) {
                                mTvCount.setText(String.valueOf(mAllCount - bad));
                            }
                            if (mEtGoodCount != null) {
                                mEtGoodCount.setText(String.valueOf(mAllCount - bad));
                            }
                            if (mBoardInfoEntity != null) {
                                mBoardInfoEntity.setPartCount(mAllCount - bad);
                                mBoardInfoEntity.setGoodCount(mAllCount - bad);
                                mBoardInfoEntity.setBadCount(bad);
                            }
                        } else {
                            flag = true;
                        }
                    }
                }
            });
        }
    }

    @OnClick(R2.id.tv_commit)
    public void onCommit() {
        if (mBoardInfoEntity != null) {
            mDisposables.add(RxRestClient.builder()
                    .loader(getContext())
                    .url("WMS/backstage/indoorTest/testAct")
                    .success(new ISuccess() {
                        @Override
                        public void onSuccess(String response) {
                            int code = new ResultConverter().getCode(response);
                            if (code == 0) {
                                ToastUtils.showToast(getContext(), "提交成功!数据未修改");
                                pop();
                            } else if (code > 0) {
                                ToastUtils.showToast(getContext(), "提交成功!等待打印标签");
                                pop();
                            } else if (code == -2) {
                                ToastUtils.showToast(getContext(), "该条记录已操作,不能在执行!");
                            } else if (code == -3) {
                                ToastUtils.showToast(getContext(), "零件数量和良品数量不相等!");
                            } else {
                                ToastUtils.showToast(getContext(), "提交失败!");
                            }
                        }
                    })
                    .error(new IError() {
                        @Override
                        public void onError(int code, String msg) {
                            ToastUtils.showToast(getContext(), msg);
                        }
                    })
                    .params("goodNum", mBoardInfoEntity.getGoodCount())
                    .params("badNum", mBoardInfoEntity.getBadCount())
                    .params("actType", 3)
                    .params("tagid", mBoardInfoEntity.getTabId())
                    .params("id", mBoardInfoEntity.getId())
                    .params("partNum", mBoardInfoEntity.getPartCount())
                    .build()
                    .unRestGet());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(priority = 1)
    public void scanEvent(ScanInfoEvent event) {
        //接收了该事件就拦截掉 不会继续往优先级小于priority的地方传递
        EventBus.getDefault().cancelEventDelivery(event);
    }
}
